package com.vastcom.springbootangular5.rest;

import com.vastcom.springbootangular5.exception.ResourceConflictException;
import com.vastcom.springbootangular5.model.User;
import com.vastcom.springbootangular5.model.UserRequest;
import com.vastcom.springbootangular5.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping(value = "/api",produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(method = GET,value = "/user/{userId}")
    public User loadById(@PathVariable Long userId){
        return this.userService.findById(userId);
    }

    @RequestMapping(method = GET,value = "/user/all")
    public List<User> loadAll(){
        return this.userService.findAll();
    }

    @RequestMapping(method = GET,value = "/usr/reset-credentials")
    public ResponseEntity<Map> resetCredentials(){
        this.userService.resetCredentials();
        Map<String,String> result=new HashMap<>();
        result.put("result","success");
        return ResponseEntity.accepted().body(result);
    }
    //查询UriComponentsBuilder的用法
    @RequestMapping(method = POST,value = "signup")
    public ResponseEntity<?> addUser(@RequestBody UserRequest userRequest, UriComponentsBuilder ucBuilder){
        User existUser=this.userService.findByUsername(userRequest.getUsername());
        if(existUser!=null){
            throw new ResourceConflictException(userRequest.getId(),"Username already exists");
        }
        User user=this.userService.save(userRequest);
        HttpHeaders headers=new HttpHeaders();
        headers.setLocation(ucBuilder.path("/api/user/{userId}").buildAndExpand(user.getId()).toUri());
       return new ResponseEntity<User>(user, HttpStatus.CREATED);
    }


    @RequestMapping("/whoami")
    @PreAuthorize("hasRole('USER')")
    public User user(){
        return (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }


}
